/*
    处理路由
    根据不同的请求方法 + 请求路径设置具体的请求处理函数

*/

var fs = require('fs')
var express = require('express')
var bodyParser = require('body-parser')
var router = express.Router() // express 封装的路由 API
var stufun = require('./student')


router.get('/students',(req,res)=>{
   
    stufun.FindAll(function(data){
        res.render('index.html',{
            students: JSON.parse(data).students
        })
        // console.log(JSON.parse(data))
    })
    
    // fs.readFile('./db.json','utf-8',(err,data)=>{  // 添加 utf-8编码后就不需要tostring()
    //     if(err) return res.static(500).send('Server error.')
    //     // var students = JSON.parse(data.toString()).students
    //     students = JSON.parse(data).students
    //     // console.log(students)
    // })
    // res.render('index.html',{
    //     apple: 'apple',
    //     students
    // })
})

router.get('/students/add',(req,res)=>{
    res.render('add.html')
})

router.post('/students/add',(req,res)=>{
    var newstu = {
        id: 0,
        name: req.body.name,
        gender: req.body.gender,
        age: req.body.age,
        hobby: req.body.hobby
    }
    stufun.Save(newstu,function(data){
        if(data)    console.log(data)
    })
    res.redirect('/students')
})

router.get('/students/edit',(req,res)=>{
    var id = req.query.id
    stufun.FindOne(id,function(stu){
        // console.log(stu)
        // if(stu.gender == )
        res.render('edit.html',stu)
    })
    
})

router.post('/students/edit',(req,res)=>{
    req.body.id = Number(req.body.id)
    console.log(req.body)
    stufun.Update(req.body,function(data){
        if(data)    console.log(data)
    })
    res.redirect('/students')
})

router.get('/students/delete',(req,res)=>{
    var id = req.query.id
    stufun.Delete(id,function(data){
        if(data)    console.log(data)
        res.redirect('/students')
    })
})

module.exports = router

/*  
module.exports = function(app){
    var students
    app.get('/students',(req,res)=>{
        fs.readFile('./db.json','utf-8',(err,data)=>{  // 添加 utf-8编码后就不需要tostring()
            if(err) return res.static(500).send('Server error.')
            // var students = JSON.parse(data.toString()).students
            students = JSON.parse(data).students
            // console.log(students)
        })
        res.render('index.html',{
            apple: 'apple',
            students
        })
    })
    
    app.get('/students/new',(req,res)=>{
        
    })
    
    app.post('/students',(req,res)=>{
        
    })
    
    app.get('/students/edit',(req,res)=>{
        
    })
    
    app.post('/students/edit',(req,res)=>{
        
    })
    
    app.get('/students/delete',(req,res)=>{
    
    })
}
*/
